﻿using CYZH.CommandAssembly.JsonObject;
using CYZH.CommandAssembly.Pojo;
using CYZH.Common;
using CYZH.Service.Drought;
using SuperWebSocket;
using SuperWebSocket.SubProtocol;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CYZH.CommandAssembly.Command
{
    public class SPI : JsonSubCommand<SPIInputParam>
    {
        protected override void ExecuteJsonCommand(WebSocketSession session, SPIInputParam commandInfo)
        {

            double[] ext = { 0, 0, 0, 0 };
            OutRasterConfigElement rce = Common.ConfigHelper.GetConfigParamByXzqhCode(commandInfo.XzqhCode);

            string strextents = rce.Extents;
            string[] strext = strextents.Split(',');

            double MinX = Convert.ToDouble(strext[0]);
            double MinY = Convert.ToDouble(strext[1]);
            double MaxX = Convert.ToDouble(strext[2]);
            double MaxY = Convert.ToDouble(strext[3]);
            ext[0] = MinX;// { MinX, MinY, MaxX, MaxY };
            ext[1] = MinY;
            ext[2] = MaxX;
            ext[3] = MaxY;

            string aoifile = rce.ShpFile;
            string cldaoiFile = rce.ChildShpFile;

            string xuncode = "";
            string leixin = "xun";
            string scaleName = "1M";
            switch (commandInfo.Scale)
            {
                case "01":
                    scaleName = "01D";
                    xuncode = "01";
                    break;
                case "02":
                    scaleName = "02D";
                    xuncode = "02";
                    break;
                case "03":
                    scaleName = "03D";
                    xuncode = "03";
                    break;
                case "04":
                    scaleName = "1M";
                    leixin = "mouth";
                    break;
                case "05":
                    scaleName = "3M";
                    leixin = "mouth";
                    break;
                default:
                    scaleName = "1M";
                    leixin = "mouth";
                    break;
            }
            

            string layername = commandInfo.XzqhCode + "_" + commandInfo.FileTime +"_"+ scaleName + "_SPI";
            //string strextents = ext[0] + ", " + ext[1] + ", " + ext[2] + ", " + ext[3];


            ResultState resultstate0 = new ResultState();
            resultstate0.process = "30";
            resultstate0.value = "查询SPI结果...";
            SendJsonMessage(session, resultstate0);
            //查询数据是否已经做过
            List<ModisResultBean> res = CommonService.querySPIRasterResult(commandInfo.XzqhCode, commandInfo.FileTime, scaleName);
            if (res.Count != 0)
            {
                //string filename = res[0].FileName;
                //string filepath = FileOper.GetExitsModisFilePath("ASC", filename, "SPI", "map");
                //string unixfile1 = filepath.Replace('\\', '/');
                MapFileResult resultstate3 = new MapFileResult();
                resultstate3.process = "100";
                resultstate3.state = "0";
                resultstate3.value = "success";
                resultstate3.LayerName = res[0].LayerName;
                resultstate3.Extents = strextents;
                //resultstate3.MapFile = unixfile1;
                SendJsonMessage(session, resultstate3);
                Logger.Singleton.Debug(String.Format("SPI结果已经存在."));
                return;
            }


            List<string> files = new List<string>();
            foreach (string filename in commandInfo.ASCFileList)
            {
                string filepath = FileOper.GenASCInFilePath(filename);

                if (!File.Exists(filepath))
                {
                    continue;
                }
                files.Add(filepath);
            }

            string aoiShpFile = FileOper.GenAOIFilePath(aoifile);
            string cldaoiShpFile = FileOper.GenAOIFilePath(cldaoiFile);
            string sfilename = FileOper.GenSPIRasterFilePath(layername);
            string ascfilename = FileOper.GenSPIASCFilePath(layername);

            ResultState resultstate = new ResultState();
            resultstate.process = "60";
            resultstate.value = "正在计算SPI...";
            SendJsonMessage(session, resultstate);

            SPIService sc = new SPIService();
            
            int rst=sc.CalculateSPI(files, aoiShpFile, sfilename, ascfilename);
            if (rst != 0)
            {
                ResultState errstate = new ResultState();
                errstate.process = "100";
                errstate.state = "-1";
                errstate.value = "计算SPI出错!";
                SendJsonMessage(session, errstate);
                return;
            }
            //生成map文件
            string mapfile = MapFileUtils.GenMapFile("SPI", strextents.Replace(',',' '), layername);
            //生成统计信息，按当前行政区划的下一级统计
            string str_static = CommonService.RegionaStatistics(sfilename, cldaoiShpFile);
            //string str_static = DroughtImgUnity.ComputeStatistics(mapfile.Replace("map", "tif"), cldaoiFile);
            //保存到数据库
            CommonService.saveSPIRasterResult(mapfile, commandInfo.FileTime, commandInfo.XzqhCode, layername, "SPI", commandInfo.FileTime.Split('-')[1], "", xuncode, leixin, str_static, scaleName);

            MapFileResult resultstate2 = new MapFileResult();
            resultstate2.process = "100";
            resultstate2.state = "0";
            resultstate2.value = "success";
            resultstate2.LayerName = layername;
            resultstate2.Extents = strextents;
            //resultstate2.MapFile = mapfile;
            SendJsonMessage(session, resultstate2);
            Logger.Singleton.Debug(String.Format("计算SPI结束，生成MAP文件路径：{0}.", mapfile));
            
        }
    }
}
